<?php

declare(strict_types=1);

namespace App\Pay\Listener;

use App\Common\Constants\Stakeholder;
use App\Order\Model\OrderModel;
use App\Order\Service\OrderGoodsService;
use App\Pay\Event\KzPayPush;
use App\Pay\Service\PayService;
use App\Resource\Service\ShopService;
use App\Third\Service\Kz\KzMainService;
use App\User\Service\MemberService;
use Hyperf\Event\Annotation\Listener;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * @Listener
 */
class KzPayPushListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            KzPayPush::class
        ];
    }

    public function process(object $event)
    {
        $orderNo = $event->orderNo;
        $field = [
            'mid',
            'order_no',
            'shop_id',
            'freight_price',
            'goods_price',
            'total_price as use_coupon_total',
            '(total_price + coupon_cut) as total_price',
            'deal_type',
            'create_at',
            'coupon_info',
            'coupon_cut',
            'entrust_discount'
        ];
        $orderInfo = OrderModel::query()
            ->selectRaw(implode(',', $field))
            ->where(['order_no' => $orderNo])
            ->first()
            ->toArray();
        $coupon = [];
        if (!empty($orderInfo['coupon_info'])){
            $coupon = json_decode($orderInfo['coupon_info'], true); // 优惠券信息
        }
        // 会员信息
        $memberInfo = $this->container->get(MemberService::class)
            ->findFirst(['mid' => $orderInfo['mid']], ['kz_cus_code','nickname','phone'])
            ->toArray();
        // 店铺信息
        $shopInfo = $this->container->get(ShopService::class)
            ->shopInfoByWhere(['shop_id' => $orderInfo['shop_id']], ['shop_name', 'shop_no']);
        //商品信息
        $goods = [];
        $goodsList = $this->container->get(OrderGoodsService::class)
            ->getOrderGoodsList(
                ['order_no' => $orderInfo['order_no']],
                ['id','goods_id','goods_title','number','selling_price','kz_goods_id','kz_type_id','kz_self_num']
            );
        foreach ($goodsList as $k => $v) {
            $goods[$k]['fShelfNum'] = $v['kz_self_num'] ?? '';
            $goods[$k]['fDiscount'] = 0;
            $goods[$k]['goodsId']    = $v['kz_goods_id'] ?? $v['goods_id'];
            $goods[$k]['typeId']    = $v['kz_type_id'] ?? 0;
            $goods[$k]['goodsName'] = $v['goods_title'];
            $goods[$k]['goodsPrice'] = bcmul((string)$v['selling_price'],'100');
            $goods[$k]['goodsNum'] = $v['number'];
            $goods[$k]['allPrice'] = bcmul((string)$goods[$k]['goodsPrice'], (string)$v['number']);
        }
        $payInfo = [];
        if (!empty($coupon) && !is_null($coupon)){
            // 使用优惠券
            foreach (json_decode($coupon['coupon'], true) as $k => $v) {
                $payInfo[$k]['payType'] = Stakeholder::KZ_PAY_COUPON;
                $payInfo[$k]['fee'] = (int)$v['deductMoney'];
                $payInfo[$k]['ticketTypeCode'] = $v['ticket_code'];
            }
            array_unshift($payInfo, ['payType' => Stakeholder::KZ_PAY_WECHAT, 'fee' => bcmul((string)$orderInfo['use_coupon_total'],'100')]);
        }else{
            // 不使用优惠券
            if ($orderInfo['total_price'] > 0) {
                $payInfo[] = [
                    "payType" => Stakeholder::KZ_PAY_WECHAT,
                    "fee" => bcmul($orderInfo['total_price'],'100')
                ];
            }
        }
        $kzPayRes = $this->container->get(KzMainService::class)->pay($memberInfo, $orderInfo, $shopInfo, $coupon, $payInfo, $goods, 'notify');
        if ($kzPayRes['code'] == 1){
            $this->container->get(PayService::class)->updateOrderGoodsDiscountInfoSelf($orderInfo, $orderInfo['coupon_cut'] > 0, $goodsList);
//            $this->container->get(PayService::class)->updateOrderGoodsDiscountInfo($orderNo, $kzPayRes, $goodsList);
        }
    }
}
